//
//  NowPlayingViewController.swift
//  Radio
//
//  Created by Mac on 2021/6/15.
//

import UIKit
import FDUIKit
import ShazamKit

class NowPlayingViewController: BaseViewController {
    
    var model = RadioResponseModelRadio()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(closeBtnAction))
        view.backgroundColor = .systemGroupedBackground

        // Do any additional setup after loading the view.
//        view.addSubview(bgImageView)
//        bgImageView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
//        view.addSubview(effectView)
//        effectView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
        view.addSubview(coverImageView)
        coverImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(CGFloat.navigationBarHeight + 40)
            make.width.height.equalTo(CGFloat.screenW / 2.5)
        }
        view.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.coverImageView.snp.bottom).offset(20)
        }
        view.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.nameLabel.snp.bottom).offset(5)
        }
        
        view.addSubview(controlView)
        controlView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(64)
            make.top.equalTo(self.descLabel.snp.bottom).offset(20)
        }
        
        controlView.addSubview(playBtn)
        playBtn.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        controlView.addSubview(favoriteBtn)
        favoriteBtn.snp.makeConstraints { make in
            make.left.equalTo(self.playBtn.snp.right).offset(20)
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.centerY.equalTo(self.playBtn);
        }
        controlView.addSubview(nightBtn)
        nightBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.centerY.equalTo(self.playBtn);
        }
        
        var image = UIImage(named: model.name)
        if image == nil {
            image = UIImage(systemName: "radio")
        }
        bgImageView.image = image
        coverImageView.image = image
        nameLabel.text = model.name
        descLabel.text = model.desc
        
        if FDAudioPlayerManager.defaultManager.playerState == .playing {
            playBtn.isSelected = false
        }else{
            playBtn.isSelected = true
        }
        favoriteBtn.isSelected = Tool.isLike(radio: model)
    }
    
    @objc func closeBtnAction(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc func shazamBtnAction(){
        if #available(iOS 15.0, *) {
            let session = SHSession()
            session.delegate = self
            
            let signatureGenerator = SHSignatureGenerator()
            do{
//                try signatureGenerator.append(<#T##buffer: AVAudioPCMBuffer##AVAudioPCMBuffer#>, at: <#T##AVAudioTime?#>)
            }catch let error{
                
            }
            
            let signature = signatureGenerator.signature()
            session.match(signature)
        } else {
            // Fallback on earlier versions
        }
        
    }
    
    @objc func playBtnAction(sender: UIButton){
        if sender.isSelected {
            FDAudioPlayerManager.defaultManager.resume()
        }else{
            FDAudioPlayerManager.defaultManager.pause()
        }
        sender.isSelected = !sender.isSelected
        
        let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as! SceneDelegate
        let tabBarC = sceneDelegate.window?.rootViewController as! TabBarController
        tabBarC.nowPlayingView?.model = model
        tabBarC.nowPlayingView?.playState = sender.isSelected ? .paused : .playing
    }
    
    @objc func favoriteBtnAction(sender: UIButton){
        if sender.isSelected {
            Tool.unlike(radio: model)
        }else{
            Tool.like(radio: model)
        }
        sender.isSelected = !sender.isSelected
        UIImpactFeedbackGenerator(style: .soft).impactOccurred()
    }
    
    @objc func nightBtnAction(sender: UIButton){
        debugPrint("nightBtnAction")
    }
    
    lazy var bgImageView: UIImageView = {
        let bgImageView = UIImageView(frame: .zero)
        bgImageView.contentMode = .scaleAspectFill
        bgImageView.clipsToBounds = true
        return bgImageView
    }()
    
    lazy var effectView: UIVisualEffectView = {
        let effectView = UIVisualEffectView(frame: .zero)
        let effect = UIBlurEffect(style: .systemMaterial)
        effectView.effect = effect
        return effectView
    }()
    
    lazy var closeBtn: UIButton = {
        let closeBtn = UIButton(frame: .zero)
        closeBtn.setTitle(NSLocalizedString("Close", comment: ""), for: .normal)
        closeBtn.setTitleColor(UIColor(hex: "333333"), for: .normal)
        closeBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        return closeBtn
    }()
    
    lazy var coverImageView: UIImageView = {
        let coverImageView = UIImageView(frame: .zero)
        coverImageView.contentMode = .scaleAspectFill
//        coverImageView.clipsToBounds = true
        
        coverImageView.layer.shadowColor = UIColor(dynamicProvider: { traitCollection in
            if traitCollection.userInterfaceStyle == .dark{
                return UIColor(hex: "ffffff").withAlphaComponent(0.2)
            }
            return UIColor(hex: "000000").withAlphaComponent(0.2)
        }).cgColor
        coverImageView.layer.shadowOffset = CGSize.zero
        coverImageView.layer.shadowOpacity = 5
        coverImageView.layer.shadowRadius = 5
        
        coverImageView.layer.cornerRadius = 10
        coverImageView.clipsToBounds = true
        
        return coverImageView
    }()
    
    lazy var nameLabel: UILabel = {
        let nameLabel = UILabel(frame: .zero)
        nameLabel.textColor = UIColor(dynamicProvider: { traitCollection in
            if traitCollection.userInterfaceStyle == .dark{
                return UIColor(hex: "ffffff")
            }
            return UIColor(hex: "333333")
        })
        nameLabel.font = .systemFont(ofSize: 16)
        return nameLabel
    }()
    
    lazy var descLabel: UILabel = {
        let descLabel = UILabel(frame: .zero)
        descLabel.textColor = UIColor(dynamicProvider: { traitCollection in
            if traitCollection.userInterfaceStyle == .dark{
                return UIColor(hex: "eaeaea")
            }
            return UIColor(hex: "777777")
        })
        descLabel.font = .systemFont(ofSize: 13)
        return descLabel
    }()
    
    lazy var controlView: UIView = {
        let controlView = UIView(frame: .zero)
        controlView.backgroundColor = UIColor(dynamicProvider: { traitCollection in
            if traitCollection.userInterfaceStyle == .dark{
                return UIColor(hex: "323232")
            }
            return UIColor(hex: "ffffff")
        })
        controlView.layer.cornerRadius = 10
        controlView.clipsToBounds = true
        return controlView
    }()
    
    lazy var playBtn: UIButton = {
        let playBtn = UIButton(frame: .zero)
        playBtn.setImage(UIImage(systemName: "pause.fill"), for: .normal)
        playBtn.setImage(UIImage(systemName: "play.fill"), for: .selected)
        playBtn.addTarget(self, action: #selector(playBtnAction), for: .touchUpInside)
        return playBtn
    }()
    
    lazy var favoriteBtn: UIButton = {
        let favoriteBtn = UIButton(frame: .zero)
        favoriteBtn.setImage(UIImage(systemName: "heart"), for: .normal)
        favoriteBtn.setImage(UIImage(systemName: "heart.fill"), for: .selected)
        favoriteBtn.addTarget(self, action: #selector(favoriteBtnAction), for: .touchUpInside)
        return favoriteBtn
    }()
    
    lazy var nightBtn: UIButton = {
        let nightBtn = UIButton(frame: .zero)
        nightBtn.setImage(UIImage(systemName: "moon.zzz"), for: .normal)
        nightBtn.setImage(UIImage(systemName: "moon.zzz.fill"), for: .selected)
        nightBtn.addTarget(self, action: #selector(nightBtnAction), for: .touchUpInside)
        return nightBtn
    }()

}

extension NowPlayingViewController: SHSessionDelegate{
    @available(iOS 15.0, *)
    func session(_ session: SHSession, didFind match: SHMatch) {
        guard let matchedMediaItem = match.mediaItems.first else { return }
        debugPrint("matchedMediaItem.title"+(matchedMediaItem.title ?? ""))
        debugPrint("matchedMediaItem.artist"+(matchedMediaItem.artist ?? ""))
        
        SHMediaLibrary.default.add([matchedMediaItem]) { error in
            if error != nil{
                //handle the error
            }
        }
    }
    @available(iOS 15.0, *)
    func session(_ session: SHSession, didNotFindMatchFor signature: SHSignature, error: Error?) {
        
    }
}
